package hn.cch.springboot_datasource.mapper;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "hn.cch.springboot_datasource.mapper.mysql", sqlSessionTemplateRef = "mysqlSqlSessionTemplate")
public class MysqlMapper {


    @Primary
    @Bean("mysqlSqlSessionFactory")
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        // Mybatis-Plus
        // MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        // MybatisConfiguration configuration = new MybatisConfiguration();
        // configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        // configuration.setJdbcTypeForNull(JdbcType.NULL);
        // sqlSessionFactory.setConfiguration(configuration);
        // sqlSessionFactory.setGlobalConfig(new GlobalConfig().setBanner(false));
        // sqlSessionFactory.setPlugins(new Interceptor[]{
        //         new PaginationInterceptor(),
        //         // 3.2.0去掉PerformanceInterceptor
        //         // new PerformanceInterceptor().setFormat(true),
        // });

        // Mybatis
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();

        // common
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mapper/mysql/**/*.xml"));
        return sqlSessionFactory.getObject();
    }



    @Primary
    @Bean(name = "mysqlSqlSessionTemplate")
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
